<template>
  <el-affix :offset="100" style="background-color: white">
    <el-container style="background-color: white">
      <el-main style="width: 400px;" v-loading.fullscreen.lock="fullscreenLoading">
        <el-card id="g-d-left-image" style="background-color: white">
          <el-image
              :src=resourceData.picture
              :fit="'contain'"
              class="image"/>
        </el-card>
      </el-main>
      <el-main>
        <el-card
            class="infoCard">
          <div>
            <h class="nftTitle">{{ resourceData.nftName }}
              <el-tag type="warning" v-if="resourceData.tag1">{{ resourceData.tag1 }}</el-tag>
              <el-tag type="success" v-if="resourceData.tag2">{{ resourceData.tag2 }}</el-tag>
              <el-tag type="danger" v-if="resourceData.tag3">{{ resourceData.tag3 }}</el-tag>
              <el-button
                  @click="feedbackView=true"
                  style="left: 650px;top: 10px;position: absolute;"
                  type="danger"
                  circle
                  text
              >
                <el-icon style="font-size: 21px">
                  <WarnTriangleFilled/>
                </el-icon>
              </el-button>
            </h>
            <el-row gutter="10" align="middle" style="margin-top: 5px">
              <el-col span="6">
                <el-avatar :src="`http://120.48.51.66:8081/user/getAvatar?username=${this.ownerObj.username}`"/>
              </el-col>
              <el-col span="6">
                <p style="display: inline;color: #999999">Owned by </p>
                <p style="color: #4C8ADA;display: inline">{{ this.ownerObj.username }}</p>
              </el-col>
              <el-col span="6">
                <el-icon style="color: #0dcc73;vertical-align: -10%;right: 5px">
                  <CircleCheckFilled/>
                </el-icon>
              </el-col>
            </el-row>
            <h style="color: #999999;top: 10px;position: relative">{{ resourceData.description }}</h>
          </div>
          <el-card
              class="insideCard">
            <template #header>
            <span style="color: #999999;align-items: center">
              <el-icon style="vertical-align: -10%"><Stamp/></el-icon> 链上位置 {{ resourceData.blockHeight }}区块<br>
              <el-icon style="vertical-align: -10%"><Timer/></el-icon> 存证时间戳 {{ resourceData.chainTime }}<br>
              <el-icon style="vertical-align: -10%"><Key/></el-icon> 链上哈希值 {{ resourceData.fileHash }}<br>
              <el-icon style="vertical-align: -10%;"><UserFilled/></el-icon> 著作权人姓名 {{ anotherName }}<br>
              <el-icon style="vertical-align: -10%"><CreditCard/></el-icon> 著作权人证件号 {{ anotherNum }}
            </span>
            </template>
            <h style="color: #999999">售价</h>
            <h class="price">{{ resourceData.price }}HNUB</h>
            <el-button
                @click="buyOwnership(this.id)"
                class="bottomBtn"
                color="#626aef"
                :dark="isDark"
                plain
                size="large"
                v-if="resourceData.status=='所有权'">购买所有权
            </el-button>
            <el-button
                @click="buyUsufruct(this.id)"
                class="bottomBtn"
                type="success"
                size="large"
                v-if="resourceData.status=='使用权'">购买使用权
            </el-button>
            <el-button
                @click="privateTalk"
                class="bottomBtn"
                id="connect-owner-btn"
                color="#4C8ADA"
                size="large"
                :dark="isDark"
                plain
                style="background-color: white">
              联系所有者
            </el-button>
          </el-card>
        </el-card>
      </el-main>
    </el-container>


    <el-dialog
        v-model="feedbackView"
        title="反馈"
        width="65%"
        ref="ruleForm"
        class="digTop"
    >

      <el-form
          ref="rulesForm"
          :model="rulesForm"
          :rules="formRules"
          label-width="140px"
      >
        <el-form-item
            label="请选择反馈类别"
            prop="selectFeed"
        >
          <el-select
              v-model="rulesForm.selectFeed"
              class="m-2"
              placeholder="请选择反馈类别"
              value-key='id'
          >
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.lable"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
            label="反馈描述"
            prop="workdesc"
        >
          <el-input v-model="rulesForm.workdesc" type="textarea" placeholder="请输入反馈描述"/>
        </el-form-item>

        <el-form-item>
          <el-button color="#626aef"
                     :dark="isDark"
                     plain @click="makeSure">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </el-affix>
</template>

<script>
import axios from "axios";
import confluxPortal from "@/conflux/conflux-portal";
import {ElMessage} from "element-plus";
// eslint-disable-next-line no-unused-vars
import conflux, {ContractCopyright, ContractCopyrightSystemTransactions, ContractHnuCoin} from "@/conflux/conflux";
import {Drip} from "js-conflux-sdk";
import {CircleCheckFilled, Stamp, Timer, Key, UserFilled, CreditCard, WarnTriangleFilled} from '@element-plus/icons-vue'
// import {isNum} from "@/page/my-onsale";

export default {
  name: "goodsDetail",

  components: {
    // eslint-disable-next-line vue/no-unused-components
    CircleCheckFilled, Stamp, Timer, Key, UserFilled, CreditCard, WarnTriangleFilled
  },

  computed: {
    userId() {
      return JSON.parse(sessionStorage.getItem('userObj')).id;
    },
    userObj() {
      return JSON.parse(sessionStorage.getItem('userObj'))
    },
  },


  created() {
    this.getData()
  },
  data() {
    return {
      goodtype: '',
      anotherName: '',
      anotherNum: '',
      options: [
        {lable: '盗版', value: 1},
        {lable: '血腥', value: 2},
        {lable: '低俗', value: 3},
      ],

      feedbackView: false,
      rulesForm: {
        selectFeed: '',
        workdesc: '',

      },
      //售单校验
      formRules: {
        selectFeed: [
          {required: true, trigger: 'blur', message: '请选择'}
        ],
        workdesc: [
          {maxlength: 300, minlength: 5, required: true, trigger: 'blur', message: '请按要求输入描述'}
        ],

      },

      replyView: false,
      reply: '',

      timer: null,
      resourceData: '',
      id: '',
      ownerObj: '',

      fullscreenLoading: false
    }
  },
  methods: {
    getType() {

    },

    getData() {
      console.log('商品id')
      console.log(this.$route.params.id)
      this.id = this.$route.params.id
      let form1 = new FormData();
      let form2 = new FormData();
      axios.get('http://120.48.51.66:8081/sale/getSaleById'
          , {
            params: {
              saleId: this.id
            }
          }).then(async response => {

        if (response.data.code == 200) {
          this.resourceData = response.data.data.sale;
          console.log(this.resourceData)
          form1.append('workId', this.resourceData.workId);
          form2.append('id', this.resourceData.userId);
          //获取拥有者对象
          axios.post('http://120.48.51.66:8081/user/getUserById', form2).then(response => {
            if (response.data.code == 200) {
              this.ownerObj = response.data.data.userInfo;
              console.log(this.ownerObj)
            } else {
              ElMessage({
                message: "获取用户详情失败",
                type: "error"
              });
            }

          })
          const tradeHash = this.resourceData.chainHash
          try{
            const result = await conflux.getTransactionByHash(tradeHash);
            const blk = await conflux.getBlockByHash(result.blockHash);
            this.resourceData.blockHeight = result.epochHeight;
            this.resourceData.chainTime = this.timestampToTime(blk.timestamp)
          }catch (e) {
            this.resourceData.blockHeight = 'null';
            this.resourceData.chainTime = 'null'
          }
          this.anotherName = this.resourceData.realName[0]
          for (let i = 1; i < this.resourceData.realName.length; i++) {
            this.anotherName += '*'
          }
          for (let i = 0; i < 3; i++) {
            this.anotherNum += this.resourceData.ownerId[i]
          }
          for (let i = 3; i < 14; i++) {
            this.anotherNum += '*'
          }
          for (let i = 14; i < 18; i++) {
            this.anotherNum += this.resourceData.ownerId[i]
          }
          console.log(this.anotherName)
        } else {
          ElMessage({
            message: "获取商品详情失败",
            type: "error"

          });

        }
      });

    },


    makeSure() {
      // this.addFeedback()
      this.$refs.rulesForm.validate(valid => {
            if (valid) {
              console.log('兜底成功')
              this.addFeedback()
              console.log(this.rulesForm.selectNft)
              this.feedbackView = false
            } else {
              console.log('兜底失败')
            }
          }
      )

    },

    addFeedback() {
      let form = new FormData();
      form.append("userId", this.userId)
      form.append("fileId", this.resourceData.id)
      form.append("fileUrl", 11)
      form.append("feedType", this.rulesForm.selectFeed)
      form.append("feedTxt", this.rulesForm.workdesc)
      form.append("fileHash", this.resourceData.fileHash)
      axios.post('http://120.48.51.66:8081/feedback/addFeedback', form).then((response) => {
        if (response.data.code == 200) {
          ElMessage({
            message: "举报成功",
            type: 'success'
          });
          console.log('举报成功')

        } else {
          this.$message({
            message: "举报失败",
            type: "error"
          });
        }
      });
    },


    privateTalk() {
      let params = new URLSearchParams()
      params.append("sendName", JSON.parse(sessionStorage.getItem('userObj')).username)
      params.append("receiveName", this.ownerObj.username)
      params.append("content", "从商品 " + this.resourceData.nftName + " 向您发起会话")
      axios.post('http://120.48.51.66:8081/inform/addMessage', params).then(function (response) {
        console.log(response)
      }).catch(function (e) {
        console.log(e)
      })
      this.$router.push('/messageBox')
    },

    //购买商品使用权
    async buyUsufruct(saleId) {
      await confluxPortal.enable();
      this.account = confluxPortal.getAccount();
      if (this.account == '') {
        ElMessage({
          message: '您还未连接conflux钱包插件',
          type: 'warning'
        });
      } else if (this.account != this.userObj.pocket) {
        ElMessage({
          message: '请使用已绑定的钱包',
          type: 'error'
        });
      } else if (Drip(await ContractHnuCoin.contract.balanceOf(this.account)).toCFX() < this.resourceData.price) {
        ElMessage({
          message: '余额不足',
          type: 'error'
        });
      } else {
        try {
          this.fullscreenLoading = true
          const transCalled = ContractCopyrightSystemTransactions.contract.download(
              this.resourceData.fileHash,
              Drip.fromCFX(this.resourceData.price).toString(),
              JSON.parse(sessionStorage.getItem('userObj')).realName,
              JSON.parse(sessionStorage.getItem('userObj')).citizenId,
          )
          console.log(transCalled);
          const transaction = await confluxPortal.sendTransaction({
            from: this.account,
            to: transCalled.to,
            data: transCalled.data,
          })
          const txHash = transaction.result;
          console.log(txHash)
          //授权
          //授权完成，插入数据库
          clearTimeout(this.timer);
          this.timer = setTimeout(() => {
            this.addUsufruct(txHash, '1')
            this.setSaleStatus(saleId, '1')
          }, 3000);
        } catch (e) {
          ElMessage({
            message: "交易失败",
            type: "error"
          });
        }
      }
    },

    //购买商品所有权
    async buyOwnership(saleId) {
      await confluxPortal.enable();
      this.account = confluxPortal.getAccount();
      if (this.account == '') {
        ElMessage({
          message: '您还未连接conflux钱包插件',
          type: 'warning'
        });
      } else if (this.account != this.userObj.pocket) {
        ElMessage({
          message: '请使用已绑定的钱包',
          type: 'error'
        });
      } else if (Drip(await ContractHnuCoin.contract.balanceOf(this.account)).toCFX() < this.resourceData.price) {
        ElMessage({
          message: '余额不足',
          type: 'error'
        });
      } else {
        //区块链
        try {
          this.fullscreenLoading = true
          const transCalled = ContractCopyrightSystemTransactions.contract.buyOwnership(
              this.account,
              this.resourceData.fileHash,
              Drip.fromCFX(this.resourceData.price).toString(),
              JSON.parse(sessionStorage.getItem('userObj')).realName,
              JSON.parse(sessionStorage.getItem('userObj')).citizenId
          )
          console.log(transCalled);
          const transaction = await confluxPortal.sendTransaction({
            from: this.account,
            to: transCalled.to,
            data: transCalled.data,
          })
          const txHash = transaction.result;
          console.log(txHash)
          ElMessage({
            message: "交易成功",
            type: "success"
          });
          clearTimeout(this.timer);
          this.timer = setTimeout(() => {
            //数据库
            this.insertTradeRecord(txHash, '2')
            this.setSaleStatus(saleId, '3')
          }, 3000);
          ElMessage({
            message: "转移所有权成功,交易完成",
            type: "success"
          });
        } catch (e) {
          console.log(e)
          ElMessage({
            message: "错误",
            type: "error"
          });
        }
      }
    },

    //插入所有权交易记录
    insertTradeRecord(txhash, status) {
      let form = new FormData()
      form.append('saleId', this.id)
      form.append('buyId', JSON.parse(sessionStorage.getItem('userObj')).id)
      form.append('txHash', txhash)
      form.append('status', status)
      axios.post('http://120.48.51.66:8081/trade/buyOwnRight', form).then(response => {
        if (response.data.code == 200) {
          ElMessage({
            message: "交易成功",
            type: "success"
          });
        } else {
          ElMessage({
            message: "插入交易记录失败，请联系管理员",
            type: "error"
          });
        }
      })
    },

    //使用权授予
    addUsufruct(txhash, status) {
      let form = new FormData()
      form.append('saleId', this.id)
      form.append('buyId', JSON.parse(sessionStorage.getItem('userObj')).id)
      form.append('txHash', txhash)
      form.append('status', status)
      axios.post('http://120.48.51.66:8081/trade/buyUseRight', form).then(response => {
        if (response.data.code == 200) {
          ElMessage({
            message: "插入交易记录成功",
            type: "success"
          });
        } else {
          ElMessage({
            message: "插入交易记录失败",
            type: "error"
          });
        }
      })
    },

    //设置售单状态
    setSaleStatus(saleId, status) {
      let form = new FormData()
      form.append('id', saleId)
      form.append('status', status)
      axios.post('http://120.48.51.66:8081/sale/changeStatus', form).then(response => {
        if (response.data.code == 200) {
          ElMessage({
            message: "修改售单数据成功",
            type: "success"
          });
          this.$router.push('/TradeCenter')
        } else {
          ElMessage({
            message: "修改售单数据失败",
            type: "error"
          });
          this.$router.push('/TradeCenter')
        }
      })
    },

    timestampToTime(cjsj) {
      const date = new Date(cjsj * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = date.getDate() + ' '
      const h = date.getHours() + ':'
      const m = date.getMinutes() + ':'
      const s = date.getSeconds()
      return Y + M + D + h + m + s;
    },

  }
}
</script>

<style scoped>
.goodslocation {
  margin-top: 0px;
  margin-left: 0px;
  height: 50%;
}

.autherlocation {
  margin-top: 0px;
  margin-left: 0px;
}

.image {
  width: 550px;
  height: 550px;
  background-color: white;
  border-radius: 12px;
  border: solid;
  margin-left: 10%;
  margin-top: -3%;
  border-color: #4C8ADA;
}

.infoCard {
  padding-left: 0px;
  width: 90%;
  left: 0%;
  top: 1%;
  border-radius: 10px;
  position: relative;
}

.writerimage {
  width: 300px;
  height: 350px;
  /*margin-top: -100px;*/
  margin-left: 10px;
}

.imgsize {
  height: 500px;
}

.detail {
  font-size: 16px;
  color: rgb(148, 137, 137);
}

.mainheight {
  height: 150%;
}

.seat {
  padding: 100px;
}

.seat2 {
  padding: 10px;
}

.seat3 {
  padding: 180px;
}

.comment {
  margin-top: -150px;
}

/* 竖线 */
.line {
  float: left;
  width: 0.1em;
  height: 550px;
  margin-right: 2em;
  margin-left: 1em;
  background: #f3f3f3;
}

/*图片轮播*/
.Img_ul {
  position: relative;
  display: flex;
  left: 36px;
  width: 322px;
  height: 50px;
  overflow: hidden;
  list-style: none;
}

.Img_li {
  float: left;
  margin: 0 8px;
  cursor: pointer;
}

.img_activeBorder {
  border: 3px solid #0dcc73;
}

.price {
  font-weight: bolder;
  color: black;
  font-size: 30px;
  display: block;
  margin-top: 10px;
}

.bottomBtn {
  margin-top: 20px;
  width: 200px;
  font-weight: bold;
  font-size: 15px;
}

.nftTitle {
  height: 30px;
  display: table;
  font-weight: bold;
  font-size: 30px;
}

.insideCard {
  margin-top: 30px;
}

/*拾起效果*/
#g-d-left-image {
  padding-right: 80px;
  background-color: #f9f9f9;
  box-shadow: none;
  margin: 0;
  transform-style: preserve-3d;
  perspective: 900px;
  transform: rotateY(0);
  transition-delay: .1s;
  border-radius: 5px;
  border: none;
}

/*拾起效果*/
#g-d-left-image:hover {
  transform: rotateY(0deg) scale(1.08);
  /*box-shadow: 0 25px 40px rgba(0, 0, 0, 0.8);*/
}

#connect-owner-btn:hover {
  color: #4C8ADA;
}

</style>

